package com.wolfalpha.lwtool.service.impl;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.google.gson.reflect.TypeToken;
import com.wolfalpha.lwtool.constant.Application;
import com.wolfalpha.lwtool.constant.Constant;
import com.wolfalpha.lwtool.exception.InternetErrorException;
import com.wolfalpha.lwtool.service.UserService;
import com.wolfalpha.lwtool.util.JsonUtil;
import com.wolfalpha.lwtool.vo.CountInfo;
import com.wolfalpha.lwtool.vo.LWJob;
import com.wolfalpha.lwtool.vo.RespMessage;

public class UserServiceImpl implements UserService {
	/**
	 * 存储数据前 用户登录
	 */
	public int login(String user, String password)
			throws InternetErrorException {
		HttpResponse message = null;
		try {
			message = Application.getClient().nonIdmpRequest(
					Constant.comLoginUrl, new BasicNameValuePair("user", user),
					new BasicNameValuePair("password", password));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String data;
		JSONObject jsonObj;
		boolean success = false;
		try {
			data = EntityUtils.toString(message.getEntity());
			System.out.println(data);
			jsonObj = new JSONObject(data);
			if (jsonObj.has("status")) {
				if (Integer.parseInt(jsonObj.getString("status")) == 1) {
					success = true;
				}
			}
		} catch (ParseException e2) {
			e2.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		// for (Iterator iter = jsonObj.keys(); iter.hasNext();) {
		// String key = (String)iter.next();
		// System.out.println(jsonObj .getString(key));
		// }
		int status = message.getStatusLine().getStatusCode();
		if (status == 200 && success) {
			System.out.println("Login Success");
			return 1;
		}

		return 0;
	}

	/***
	 * 发布兼职
	 * 
	 */
	@Override
	public int publishJob(String name, int category, String contact,
			String tel, int region, String address, int type, int wage,
			int wageType, int payoff, int time, String days, int limit,
			String intro, String requirement) throws InternetErrorException {
		HttpResponse message = null;
		try {
			message = Application
					.getClient()
					.unSafeIdmpRequest(
							Constant.comUrl + "publish",
							new BasicNameValuePair("name", name),
							new BasicNameValuePair("category", String
									.valueOf(category)),
							new BasicNameValuePair("contact", contact),
							new BasicNameValuePair("tel", tel),
							new BasicNameValuePair("region", String
									.valueOf(region)),
							new BasicNameValuePair("address", address),
							new BasicNameValuePair("type", String.valueOf(type)),
							new BasicNameValuePair("wage", String.valueOf(wage)),
							new BasicNameValuePair("wage_type", String
									.valueOf(wageType)),
							new BasicNameValuePair("payoff", String
									.valueOf(payoff)),
							new BasicNameValuePair("time", String.valueOf(time)),
							new BasicNameValuePair("days", days),
							new BasicNameValuePair("limit", String
									.valueOf(limit)),
							new BasicNameValuePair("intro", intro),
							new BasicNameValuePair("requirement", requirement));
		} catch (Exception e) {
			e.printStackTrace();
		}

		int status = message.getStatusLine().getStatusCode();
		if (status == 200) {
			return 1;// 成功
		} else {
			return 0;
		}
	}

	/**
	 * 获取发布的兼职列表
	 */
	@Override
	public List<LWJob> getPublishedList(boolean expired, boolean closed,
			boolean deleted, int page, int limit) throws Exception {
		HttpResponse message;
		try {
			message = Application.getClient().safeIdmpRequest(
					Constant.comUrl + "getPublishedList",
					new BasicNameValuePair("expired", expired ? "1" : "0"),
					new BasicNameValuePair("closed", closed ? "1" : "0"),
					new BasicNameValuePair("deleted", deleted ? "1" : "0"),
					new BasicNameValuePair("page", String.valueOf(page)),
					new BasicNameValuePair("limit", String.valueOf(limit)));
		} catch (Exception e) {
			throw new Exception();
		}
		String data;
		JSONObject jsonObj;
		try {
			data = EntityUtils.toString(message.getEntity());
			jsonObj = new JSONObject(data);
			System.out.println("getPublishList:" + jsonObj.getInt("status")
					+ jsonObj);
			if (jsonObj.has("status")) {
				if (jsonObj.getInt("status") == 1) {
					java.lang.reflect.Type type = new TypeToken<ArrayList<LWJob>>() {
					}.getType();
					List<LWJob> jobList = JsonUtil.parseJson(
							jsonObj.getString("data"), type);
					if (jobList == null) {
						return new ArrayList<LWJob>();
					}
					return jobList;
				}
			}
		} catch (ParseException e2) {
			e2.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 修改自己的兼职
	 * 
	 * @param spec
	 *            1:删除
	 * @param spec
	 *            2:关闭
	 * @param jobid
	 *            :兼职ID
	 */
	@Override
	public boolean modifyMyJob(int spec, int jobid) throws Exception {
		HttpResponse message = null;
		try {
			if (spec == 2) {
				message = Application.getClient().unSafeIdmpRequest(
						Constant.comUrl + "close",
						new BasicNameValuePair("id", String.valueOf(jobid)));
			} else if (spec == 1) {
				message = Application.getClient().unSafeIdmpRequest(
						Constant.comUrl + "delete",
						new BasicNameValuePair("id", String.valueOf(jobid)));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String data;
		JSONObject jsonObj;
		try {
			data = EntityUtils.toString(message.getEntity());
			jsonObj = new JSONObject(data);
			System.out.println("Modify:" + jsonObj);
			if (jsonObj.has("status")) {
				if (jsonObj.getBoolean("status")) {
					return true;
				}
			}
		} catch (ParseException e2) {
			e2.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return false;
	}

	/***
	 * 管理员登录
	 */
	@Override
	public boolean adminLogin(String mobile, String email) throws Exception {
		HttpResponse message = null;
		try {
			message = Application.getClient().nonIdmpRequest(
					Constant.adminLoginUrl,
					new BasicNameValuePair("mobile", mobile),
					new BasicNameValuePair("password", email));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String data;
		JSONObject jsonObj;
		boolean success = false;
		try {
			data = EntityUtils.toString(message.getEntity());
			jsonObj = new JSONObject(data);

			System.out.println("admin login:" + jsonObj);

			if (jsonObj.has("status")) {
				if (jsonObj.getBoolean("status")) {
					success = true;
				}
			}
		} catch (ParseException e2) {
			e2.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return success;
	}

	/**
	 * 获取统计数据
	 * 
	 * @return
	 */
	@Override
	public CountInfo adminGetCount() throws Exception {
		HttpResponse message = null;
		try {
			message = Application.getClient().safeIdmpRequest(
					Constant.adminGetCountUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String data;
		JSONObject jsonObj;
		try {
			data = EntityUtils.toString(message.getEntity());
			jsonObj = new JSONObject(data);
			System.out.println("acount:" + jsonObj);
			if (jsonObj.has("status")) {
				if (jsonObj.getBoolean("status")) {
					RespMessage jjson = JsonUtil.parseJson(data,
							RespMessage.class);
					return jjson.getData();
				}
			}
		} catch (ParseException e2) {
			e2.printStackTrace();
			return null;
		} catch (IOException e2) {
			e2.printStackTrace();
			return null;
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}

	/**
	 * @param spec
	 */
	@Override
	public void adminGetNuaudite(int spec) throws Exception {
		// HttpResponse message = null;
		// try {
		// message = Application.getClient().safeIdmpRequest(
		// Constant.adminGetCountUrl);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// String data;
		// JSONObject jsonObj;
		// try {
		// data = EntityUtils.toString(message.getEntity());
		// jsonObj = new JSONObject(data);
		// System.out.println("acount:" + jsonObj);
		// if (jsonObj.has("status")) {
		// if (jsonObj.getBoolean("status")) {
		// RespMessage jjson = JsonUtil.parseJson(data,
		// RespMessage.class);
		// // return jjson.getData();
		// }
		// }
		// } catch (ParseException e2) {
		// e2.printStackTrace();
		// } catch (IOException e2) {
		// e2.printStackTrace();
		// } catch (JSONException e) {
		// e.printStackTrace();
		// }
		// return null;
	}

	/**
	 * 查看未审核的信息
	 * 
	 * @param spec
	 *            1：兼职
	 * @param spec
	 *            2:企业
	 */
	@Override
	public String adminViewInfo(int spec) throws Exception {
		String info = "";
		HttpResponse message = null;
		try {
			if (spec == 2)
				message = Application.getClient().safeIdmpRequest(
						Constant.adminIndexComUrl);
			else if (spec == 1)
				message = Application.getClient().safeIdmpRequest(
						Constant.adminIndexJobUrl);
			else {
				return info;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String data;
		JSONObject jsonObj;
		try {
			data = EntityUtils.toString(message.getEntity());
			jsonObj = new JSONObject(data);
			System.out.println("acount:" + jsonObj);
			if (jsonObj.has("status")) {
				if (jsonObj.getBoolean("status")) {
					if (jsonObj.has("data"))
						info = jsonObj.getString("data");
				}
			}
		} catch (ParseException e2) {
			e2.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return info;
	}

	/***
	 * 审核
	 * 
	 * @param spec
	 *            :1兼职2企业
	 * @param id
	 * @param isPass
	 * @param reason
	 * @param detail
	 */
	@Override
	public boolean adminAudite(int spec, int id, int isPass, String reason,
			String detail) throws Exception {
		HttpResponse message = null;
		try {
			if (spec == 2)
				message = Application.getClient()
						.nonIdmpRequest(
								Constant.adminAuditeComUrl + "id/"
										+ String.valueOf(id)
										+ ".html?format=json",
								new BasicNameValuePair("isPass", String
										.valueOf(isPass)),
								new BasicNameValuePair("reason", reason),
								new BasicNameValuePair("detail", detail));
			else if (spec == 1)
				message = Application.getClient()
						.nonIdmpRequest(
								Constant.adminAuditeJobUrl + "id/"
										+ String.valueOf(id)
										+ ".html?format=json",
								new BasicNameValuePair("isPass", String
										.valueOf(isPass)),
								new BasicNameValuePair("reason", reason),
								new BasicNameValuePair("detail", detail));

			else {
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		String data;
		JSONObject jsonObj;
		try {

			data = EntityUtils.toString(message.getEntity());
			if (!data.contains("<html")) {
				jsonObj = new JSONObject(data);
				System.out.println("acount:" + jsonObj);
				if (jsonObj.has("status")) {
					if (jsonObj.getBoolean("status")) {
						return true;
					}
				}
			}
		} catch (ParseException e2) {
			e2.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return false;
	}

	/***
	 * 审核查看执照
	 * 
	 * @param id
	 * @return last url
	 */
	@Override
	public String getComLicPic(int id) throws Exception {
		HttpResponse message = null;
		try {
			message = Application.getClient().safeIdmpRequest(
					Constant.adminComInfoUrl + "&id=" + String.valueOf(id));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String data;
		JSONObject jsonObj;
		try {

			data = EntityUtils.toString(message.getEntity());
			System.out.println(data);
			jsonObj = new JSONObject(data);
			if (jsonObj.has("status")) {
				if (jsonObj.getBoolean("status")) {
					String data1 = jsonObj.getString("data");
					data1 = data1.replaceAll("\"|\\\\", "");
					Pattern p = Pattern.compile("lic_url.*?png");
					Matcher m = p.matcher(data1);
					if (m.find()) {
						return m.group().split(":")[1];
					}
				}
			}
		} catch (ParseException e2) {
			e2.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 加载图片
	 * 
	 * @param url
	 * @return Bitmap
	 */
	@Override
	public Bitmap getImage(String u_path) {
		Bitmap bitmap = null;
		try {
			System.out.println(u_path);
			URL url = new URL(u_path); // path图片的网络地址
			// try {
			// Application.getClient().safeIdmpRequest(u_path);
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				bitmap = BitmapFactory.decodeStream(httpURLConnection
						.getInputStream());
				System.out.println("加载网络图片完成");
			} else {
				System.out.println("加载网络图片失败");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}
}
